﻿using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace IOP.AspNetCore.Extension.Swagger
{
    /// <summary>
    /// 用于Swagger的HTTP操作类
    /// </summary>
    public class HttpHeaderOperation : IOperationFilter
    {
        /// <summary>
        /// 过滤器，查找存在验证的API
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            context.ApiDescription.TryGetMethodInfo(out MethodInfo info);
            if (info.CustomAttributes.Any(x => x.AttributeType == typeof(AuthorizeAttribute)) ||
                info.DeclaringType.CustomAttributes.Any(x => x.AttributeType == typeof(AuthorizeAttribute)))
            {
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "Authorization",
                    In = "header",
                    Type = "string",
                    Required = true
                });
            }
        }
    }
}
